package com.test.mchelepesa.util_rice.http_rice;

import static com.test.mchelepesa.bean_rice.StaticConfig_rice.Upload_Info_Url;
import static com.test.mchelepesa.constant_rice.Url_rice.*;

import android.text.TextUtils;

import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseApplication_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.BindAccountActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.FaceInfoActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.OcrInfoActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.login_rice.VerificationActivity;
import com.test.mchelepesa.bean_rice.StaticConfig_rice;
import com.test.mchelepesa.dialog_rice.MsgDialog;
import com.test.mchelepesa.dialog_rice.RequestFailedDialog;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.activity_fragment_rice.MainActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.ServiceFeedbackActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseInfoActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseLoginActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.loan_rice.LoanApplyActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.loan_rice.LoanMainActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.login_rice.LoginPhoneNumActivity_rice;
import com.test.mchelepesa.bean_rice.config_info_rice.AppShowInfo_rice;
import com.test.mchelepesa.bean_rice.config_info_rice.GlobalConfig_rice;
import com.test.mchelepesa.bean_rice.process_rice.ProcessInfo_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.BankAccountList_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.LoanApplyDetailInfo_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.LoanLimitInfo_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.LoginInfo_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.RepayH5Info_gn_cl_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.RepayH5Info_ug_ke_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.RepayInfo_rice;
import com.test.mchelepesa.dialog_rice.LoadingDialog_rice;
import com.test.mchelepesa.util_rice.analytics_rice.event_rice.IAnalyticsEvent_rice;
import com.test.mchelepesa.util_rice.analytics_rice.util_rice.AnalyticsUtil_rice;
import com.test.mchelepesa.util_rice.helper_rice.UserInfoHelper_rice;
import com.test.mchelepesa.bean_rice.rate_rice.StarWindowConfig_rice;

import org.json.JSONArray;
import org.json.JSONObject;

public class HttpPresenter_rice {

    private static class Inner {
        private static final HttpPresenter_rice instance = new HttpPresenter_rice();
    }

    private HttpPresenter_rice() {}

    public static HttpPresenter_rice getInstance() {
        return Inner.instance;
    }

    private BaseActivity_rice activity;

    public LoadingDialog_rice progressBarDialog;

    public void setActivity(BaseActivity_rice activity) {
        if (progressBarDialog != null && progressBarDialog.isShowing()) {
            progressBarDialog.dismiss();
        }
        if (activity != null) progressBarDialog = new LoadingDialog_rice(activity);
        this.activity = activity;
    }

    public void progressBarDialogShow() {
        if (progressBarDialog == null) return;
        progressBarDialog.show();
    }

    public void progressBarDialogDismiss() {
        if (progressBarDialog == null) return;
        progressBarDialog.dismiss();
    }

    public void showReloadDialog(Runnable reloadRunnable){
        if (activity!=null && !activity.isClose()){

            try {
                new RequestFailedDialog(activity, reloadRunnable).show();
            }catch (Exception e){
                StringUtil_rice.printException(e);
            }

        }
    }

    public void showReloadDialog2(Runnable reloadRunnable){
        if (activity!=null && !activity.isClose()){

            try {
                new RequestFailedDialog(activity, true, reloadRunnable).show();
            }catch (Exception e){
                StringUtil_rice.printException(e);
            }

        }
    }

    public void showToastOnUiThread(String text) {
        if (activity != null) {
            activity.showToastOnUiThread_rice(text);
        }
    }

    public String getLanguage(){
        if (activity==null) return BaseApplication_rice.gApplication_rice().getString(R.string.language);
        return activity.getString(R.string.language);
    }

    //通知Activity处理响应
    public void notifyActivityHandleResponse(String word, JSONObject responseJson) {
        if (activity == null) return;
        try {
            String gcode = responseJson.optString("code");
            String gmsg = StringUtil_rice.getSafeString(responseJson.optString("msg"));
            Object gobj = responseJson.opt("obj");

            //失败响应
            if (StringUtil_rice.safeParseInt(gcode)!=0) {
                onResponseFail(word,gmsg);
                return;
            }

            //成功响应
            onResponseSuccess(word,gmsg,gobj);

        } catch (Exception e) {
            StringUtil_rice.printException(e);
        }
    }

    //成功响应
    private void onResponseSuccess(String word,String gmsg,Object gobj){
        if (gobj instanceof JSONObject) {
            JSONObject objJsonObject = (JSONObject) gobj;
            if (word.equalsIgnoreCase(Upload_Info_Url)||(StaticConfig_rice.getCountryUrlPrefix() + word).equalsIgnoreCase(Upload_Info_Url)){
                if (activity instanceof BaseInfoActivity_rice) ((BaseInfoActivity_rice) activity).onInfoUploadResponse_rice();
                return;
            }
            switch (word) {
//                    case PATH_APP_VERSION://查询App版本更新
//                        AppVersionInfo.parse(objJsonObject);
//                        if (activity instanceof MainActivity) ((MainActivity) activity).onQueryAppVersionResponse();
//                        break;
                case PATH_GLOBAL://global配置
                    GlobalConfig_rice.parse(objJsonObject);
                    if (activity instanceof MainActivity_rice) ((MainActivity_rice) activity).onGlobalResponse();
                    break;
                case PATH_APP_SHOW_INFO://获取配置信息
                    AppShowInfo_rice.parse(objJsonObject);
                    if (activity instanceof LoginPhoneNumActivity_rice) ((LoginPhoneNumActivity_rice) activity).onAppShowInfoResponse();
                    else if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onAppShowInfoResponse();
                    break;
                case PATH_LOGIN_NO_CODE://用户登录
                    LoginInfo_rice.parse(objJsonObject);
                    if (activity instanceof BaseLoginActivity_rice) ((BaseLoginActivity_rice) activity).onUserLoginResponse_rice();
                    break;
                case PATH_FEED_BACK://提交反馈
                    if (activity instanceof ServiceFeedbackActivity_rice) ((ServiceFeedbackActivity_rice) activity).onSubmitServiceFeedback();
                    break;
                case PATH_BIND_BANK_ACCOUNT://新增钱包（科特）
                    boolean addBindFlag = "YES".equalsIgnoreCase(objJsonObject.optString("addBindFlag"));
                    String channel = StringUtil_rice.getSafeString(objJsonObject.optString("channel"));
                    if (activity instanceof BindAccountActivity_rice) ((BindAccountActivity_rice) activity).onAddAccountResponse(addBindFlag,channel);
                    else if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onAddAccountResponse(addBindFlag,channel);
                    break;
                case PATH_DELETE_BOUND_BANK_ACCOUNT://删除钱包（科特）
                    if (activity instanceof BindAccountActivity_rice) ((BindAccountActivity_rice) activity).onDeleteAccountResponse();
                    else if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onDeleteAccountResponse();
                    break;
                case PATH_USER_PROCESS://用户流程状态
                    ProcessInfo_rice.parse(objJsonObject.toString());
                    activity.onUserProcessResponse_rice();
                    break;
                case PATH_LOAN_LIMIT://额度信息
                    LoanLimitInfo_rice.parse(objJsonObject);
                    if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onLoanLimitInfoResponse();
                    break;
                case PATH_GET_LOAN_APPLY_DETAIL://借款页信息
                    LoanApplyDetailInfo_rice.parse(objJsonObject);
                    if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onLoanApplyDetailResponse();
                    else if (activity instanceof BaseInfoActivity_rice) ((BaseInfoActivity_rice) activity).onLoanApplyDetailResponse_rice();
                    else if (activity instanceof LoanApplyActivity_rice) ((LoanApplyActivity_rice) activity).onLoanApplyDetailResponse();
                    break;
                case PATH_LOAN_APPLY://发起借款申请响应
//                        AFInstallHelper.getInstance().saveEventInfo(AFInstallHelper.AFEvent.AT_LOAN_APPLY);
//                        FirebaseHelper.getInstance().saveEventInfo(AFInstallHelper.AFEvent.AT_LOAN_APPLY);
                    AnalyticsUtil_rice.INSTANCE.addEvent(IAnalyticsEvent_rice.AT_LOAN_APPLY);
                    if (activity instanceof LoanApplyActivity_rice) ((LoanApplyActivity_rice) activity).onLoanApplyResponse();
                    break;
                case PATH_REPAY_INFO://还款信息展示
                    RepayInfo_rice.parse(objJsonObject);
                    if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onRepayDetailResponse();
                    break;
                case PATH_ORDER_REPAY_H5://获取还款Url（加纳、科特）
                    RepayH5Info_gn_cl_rice.parse(objJsonObject);
                    if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onOrderRepayH5Response(RepayH5Info_gn_cl_rice.getInstance().getUrl());
                    break;
                case PATH_GET_ORDER_REPAY_H5://获取还款Url（乌干达、肯尼亚）
                    RepayH5Info_ug_ke_rice.parse(objJsonObject);
                    if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onOrderRepayH5Response(RepayH5Info_ug_ke_rice.getInstance().getUrl());
                    break;
                case PATH_CREATE_VIRTUAL_ACCOUNT://线下还款-创建虚拟账号还款（尼日）
                    if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onInitOfflinePayChannelResponse();
                    break;
                case Path_Face_Recognition_Check://上传人脸照片信息响应(越南)
                    if (activity instanceof BaseInfoActivity_rice) ((BaseInfoActivity_rice) activity).onInfoUploadResponse_rice();
                    break;
                case Path_Save_Perator_Information://保存运营商认证信息(越南)
                    if (activity instanceof BaseInfoActivity_rice) ((BaseInfoActivity_rice) activity).onInfoUploadResponse_rice();
                    break;
                case PATH_UPLOAD_IMAGE_FILE://图片上传响应
                    String url = objJsonObject.optString("url");
                    if (activity instanceof FaceInfoActivity_rice) ((FaceInfoActivity_rice)activity).onImageUploadSuccess(url);
                    else if (activity instanceof OcrInfoActivity_rice) ((OcrInfoActivity_rice)activity).onPhotoUploadResponse(url);
                    break;
                case PATH_FETCH_STAR_WINDOW_CONFIG://评分弹窗配置
                    StarWindowConfig_rice.parse(objJsonObject);
                    if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice)activity).onStarWindowConfigResponse();
                    break;
                case PATH_OCR_INFO:
                    HttpManager_rice.getInstance().requestUserProcess();
                    break;
                case PATH_SEND_WHATSAPP_MESSAGE:
                    if (activity instanceof VerificationActivity) ((VerificationActivity)activity).onGetCodeSuccessful();
                    break;
                case PATH_CHECK_WHATSAPP_CODE:
                    if (activity instanceof  VerificationActivity) ((VerificationActivity)activity).onCheckSuccessful();
                    break;
                case PATH_DROP_USER_DATA:
                    if ("GET".equalsIgnoreCase(UserInfoHelper_rice.getInstance().dropType())){
                        String showDropButton = objJsonObject.optString("showDropButton");
                        UserInfoHelper_rice.getInstance().sShowDropButton(showDropButton);
                        if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onDropConfigResponse();
                    }else if ("DROP".equalsIgnoreCase(UserInfoHelper_rice.getInstance().dropType())) activity.onUserCancel();
                    break;
                default:
                    //throw new IllegalStateException("Unexpected value: " + word);
            }
        } else if (gobj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) gobj;
            switch (word) {
                case PATH_FETCH_BOUND_BANK_ACCOUNT://获取钱包列表（科特）
                    BankAccountList_rice.parse(jsonArray);
                    if (activity instanceof BindAccountActivity_rice) ((BindAccountActivity_rice) activity).onFetchAccountListResponse();
                    else if (activity instanceof LoanMainActivity_rice) ((LoanMainActivity_rice) activity).onFetchBankAccountListResponse();
                    break;
            }
        } else {
            //其它类型
            gmsg = StringUtil_rice.getSafeString(gmsg);
            if (TextUtils.isEmpty(gmsg)) {
                gmsg = "Response something error";
            }
            activity.showToast_rice(gmsg);
        }
    }

    //失败响应
    private void onResponseFail(String word,String gmsg){

        if (PATH_SMS_CODE.equalsIgnoreCase(word)){
            new MsgDialog(activity,gmsg,null).show();
            return;
        }

        if (PATH_LOGIN_NO_CODE.equalsIgnoreCase(word)){
            new MsgDialog(activity,gmsg,null).show();
            return;
        }

        activity.showToast_rice(gmsg);
    }

}
